/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.constant.PunishMainServicePortUriConstant;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.enums.DocumentTemplateKindEnum;
import com.icinfo.cloud.provider.common.enums.DocumentTemplateTypeEnum;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.HeaderUtil;
import com.icinfo.cloud.provider.common.utils.ImageUtil;
import com.icinfo.cloud.provider.common.utils.PunishMainClientUtil;
import com.icinfo.cloud.provider.exception.BusinessException;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.FillAndConvertToPdfRequest;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentRecordStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.common.publicsecurityentrust.dto.PublicSecurityDocumentNumberRollbackDTO;
import com.icinfo.cloud.provider.punish.common.seal.dto.FileSealInfoQueryDto;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.dto.*;
import com.icinfo.cloud.provider.punish.mapper.*;
import com.icinfo.cloud.provider.punish.model.AppDocumentRelatedGoods;
import com.icinfo.cloud.provider.punish.service.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseDocumentRecordDelRequest;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.HandleTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartiesReasonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseDocumentRecordVo;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.model.CaseDocumentSendinfoConfirm;
import com.icinfo.cloud.provider.punish.ucase.payment.dto.CasePaymentSlipNumberSaveDto;
import com.icinfo.cloud.provider.punish.ucase.payment.enums.PayWayEnum;
import com.icinfo.cloud.provider.punish.vo.AppAskNoticeDocumentVo;
import com.icinfo.cloud.provider.punish.vo.AppRelationDocumentListVo;
import com.icinfo.cloud.provider.punish.vo.CaseDocumentRecordSimpleVo;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 描述: 案件文书记录表-TRJ case_document_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年02月15日
 */
@Service
@Slf4j
@Transactional(rollbackFor = {Error.class, Exception.class})
public class CaseDocumentRecordServiceImpl extends MyBatisServiceSupport implements ICaseDocumentRecordService {

    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Resource
    private CasePartiesRecordMapper casePartiesRecordMapper;

    @Resource
    CaseReasonMainRecordMapper caseReasonMainRecordMapper;


    @Resource
    private IAppCaseBeforeDocumentRecordService appCaseBeforeDocumentRecordService;

    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private CaseRelatedDocumentRecordMapper caseRelatedDocumentRecordMapper;
    @Resource
    private CaseDocumentSendinfoConfirmMapper caseDocumentSendinfoConfirmMapper;
    /*@Resource
    private StageDocCommonOperateClient stageDocCommonOperateClient;*/
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Resource
    private ICaseMainDetailSimpleInfoService caseMainDetailSimpleInfoService;
    @Resource
    private AppDocumentRelatedGoodsMapper appDocumentRelatedGoodsMapper;
    @Value("${tzService.url}")
    private String url;
    @Resource
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private ISimpleCaseService simpleCaseService;
    @Resource
    private AppCaseBeforeDocumentRecordServiceImpl appCaseBeforeDocumentRecordServiceImpl;
    @Resource
    private ConfigBusiParamDocumentInfoMapper configBusiParamDocumentInfoMapper;
    /**
     * 描述： 简易处罚接受签字捺印
     *
     * @return {@link Map< String, Object>}
     * @author: zhengqiang
     * @date: 2022/7/22
     * @param: saveDto
     **/
    @Override
    public Map<String, Object> receiveSignFileOfSimple(SimpleCaseSignSaveDto saveDto) {
        Map resultMap = new HashMap();

        //得到简易程序文书种类列表
        List<String> simpleCaseDocs = getSimpleCaseDocs(saveDto);


        //查询交易处罚文书列表
        Example queryExample = new Example(CaseDocumentRecord.class);
        queryExample.createCriteria().andEqualTo("caseId", saveDto.getCaseId()).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(queryExample);
        if (ObjectUtils.isEmpty(caseDocumentRecords)) {
            throw new BusinessException("案件id对应文书不存在-caseId:" + saveDto.getCaseId());
        }

        boolean isSuccess = true;
        List docResultList = new ArrayList();
        for (CaseDocumentRecord e : caseDocumentRecords) {
            Map docResultMap = new HashMap();
            CaseDocumentRecordSignSaveDto dto = new CaseDocumentRecordSignSaveDto();
            dto.setDocumentId(e.getId());
            dto.setSignFile(saveDto.getSignFile());
            dto.setFingerprint(saveDto.getFingerprint());
            dto.setDocumentCatalogCode(e.getDocumentCatalogCode());
            //查询文书种类
            ConfigBusiParamDocumentInfo detailByDocumentCatalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(e.getDocumentCatalogCode());
            String kindCode = detailByDocumentCatalogCode.getDocumentKindCode();
            if (!simpleCaseDocs.contains(kindCode)) {
                continue;
            }
            Map<String, Object> stringObjectMap = receiveSignFileOfCaseDoc(dto);
            if (!"true".equals(stringObjectMap.get("success"))) {
                isSuccess = false;
                break;
            }
            docResultMap.put("documentCatalogCode", e.getDocumentCatalogCode());
            docResultMap.put("pdfSealUrl", stringObjectMap.get("pdfSealUrl"));
            docResultList.add(docResultMap);
        }

        if (!isSuccess) {
            resultMap.put("success", false);
        } else {
            resultMap.put("success", true);
            resultMap.put("docResultList", docResultList);
        }
        return resultMap;
    }

    /**
     * 获取案件的documentKindCode
     * @param saveDto
     * @return
     */
    private List<String> getSimpleCaseDocs(SimpleCaseSignSaveDto saveDto) {

        CaseMainDetailSimpleInfo simpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(saveDto.getCaseId());
        JSONObject jsonObject = JSONObject.parseObject(simpleInfo.getCaseContent());
        String isPublicSecurity = jsonObject.getString("isPublicSecurity");
        if(StrUtil.equals(isPublicSecurity, "1")){
            // 如果是公安委托执法 则生成公安委托执法对应的文书
            return Arrays.asList(DocumentKindEnum.DOC_KIND_JYCXGAWTCFJDS.getCode(), DocumentKindEnum.DOC_KIND_XCZPJSM.getCode());
        }
        return Arrays.asList(DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode(), DocumentKindEnum.DOC_KIND_XCZPJSM.getCode());
    }


    /**
     * 签字捺印 接收 签字 指纹
     *
     * @param saveDto
     * @return
     */
    @Override
    public Map<String, Object> receiveSignFileOfCaseDoc(CaseDocumentRecordSignSaveDto saveDto) {
        // 文书表更新
        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(saveDto.getDocumentId());
        if (caseDocumentRecord == null) {
            throw new BusinessException("文书不存在，请检查");
        }
        String caseId = caseDocumentRecord.getCaseId();
        CaseMainInfo caseMainInfo=caseMainInfoMapper.selectByPrimaryKey(caseId);
        //判断文书目录编码与查询出的文书是否一致
        if (!caseDocumentRecord.getDocumentCatalogCode().equals(saveDto.getDocumentCatalogCode())) {
            throw new BusinessException("入参documentId查询的文书目录编码【" + caseDocumentRecord.getDocumentCatalogCode() + "】与入参documentCatalogCode【" + saveDto.getDocumentCatalogCode() + "】不一致");
        }

        JSONObject jsonObject = JSON.parseObject(caseDocumentRecord.getDocumentContent());
        //    jsonObject.put("QM", StringUtils.isNotBlank(saveDto.getSignFile()) ? saveDto.getSignFile(): "");
        //  jsonObject.put("NY",StringUtils.isNotBlank(saveDto.getFingerprint()) ? saveDto.getFingerprint() : "");
        //签名base64优化成地址 20230522
        String base64Str = ImageUtil.overlapImage(saveDto.getSignFile(), saveDto.getFingerprint());
        //String ossUrl = appCaseBeforeDocumentRecordService.base64ToOssUrl(base64Str);
        // PC送达方式签字得特殊处理.
        if("1".equals(caseMainInfo.getIsMobile())){
            jsonObject.put("ZLB_QM", base64Str);
        }
        // 这里需要判断是否选择签字
        if (StrUtil.isNotBlank(saveDto.getNotSignReason())){
            String notSignReason = appCaseBeforeDocumentRecordService.getNotReasonStr(saveDto.getNotSignReason(), saveDto.getNotSignReasonReplenish());
            jsonObject.put("notSignReason", notSignReason);
        }else {
            jsonObject.put("signFingerprintPic", base64Str);
            jsonObject.put("signFingerprintDate", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
        }
        List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos = appCaseBeforeDocumentRecordService.getConfigBusiParamDocumentInfos(caseDocumentRecord.getDocumentCatalogCode());
        //查询当事人类型
        Example queryExample = new Example(CasePartiesRecord.class);
        queryExample.createCriteria().andEqualTo("caseId", caseDocumentRecord.getCaseId()).andEqualTo("status", "1");
        ;
        List<CasePartiesRecord> casePartiesRecord = casePartiesRecordMapper.selectByExample(queryExample);
        if (ObjectUtils.isEmpty(casePartiesRecord)) {
            throw new BusinessException("未找到当事人信息");
        }
        String partyType = casePartiesRecord.get(0).getPartyType();
        String templateCode = caseDocumentRecord.getDocumentTemplateCode();
        if (ObjectUtils.isEmpty(templateCode)){
            templateCode = appCaseBeforeDocumentRecordService.getTemplateCodeByDocumentCatalogCode(configBusiParamDocumentInfos, partyType,saveDto.getCaseType());
        }
        ConfigBusiParamDocumentInfo detailByDocumentCatalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(caseDocumentRecord.getDocumentCatalogCode());
        String kindCode = detailByDocumentCatalogCode.getDocumentKindCode();
        // 回滚或预警信息
        PublicSecurityDocumentNumberRollbackDTO rollback = new PublicSecurityDocumentNumberRollbackDTO();
        rollback.setRollback(Boolean.FALSE);
        //简易处罚获取二维码,生成行政行为码
        //List payInfoList= new ArrayList();
        if (Arrays.asList(DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode(), DocumentKindEnum.DOC_KIND_JYCXGAWTCFJDS.getCode())
                .contains(kindCode)) {
            //查询行政行为码是否已经生成
           /* CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
            String caseQrCodeUrl = caseMainInfo.getCaseQrCodeUrl();
            String caseBarCodeUrl = caseMainInfo.getCaseBarCodeUrl();
            if (ObjectUtils.isEmpty(caseQrCodeUrl) && ObjectUtils.isEmpty(caseBarCodeUrl)) {
                //生成行政行为码
                Map<String, String> codeMap = simpleCaseService.getCaseQRCode(caseId);
                if (ObjectUtil.isNotEmpty(codeMap)) {
                    caseQrCodeUrl = codeMap.get("caseQrCodeUrl");
                    caseBarCodeUrl = codeMap.get("caseBarCodeUrl");
                }
            }
            //设置行政行为码
            jsonObject.put("qrCodeUrl", caseQrCodeUrl);
            jsonObject.put("barCodeUrl", caseBarCodeUrl);*/
            // 得到简易程序宽表信息
            CaseMainDetailSimpleInfo simpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseId);
            JSONObject contentObject = JSONObject.parseObject(simpleInfo.getCaseContent());
            // 得到是否为公安委托执法
            String isPublicSecurity = contentObject.getString("isPublicSecurity");
            String clientOrgCode = contentObject.getString("clientOrgCode");
            //获取文号
            String documentNumber = caseDocumentRecord.getDocumentNumber();
            if (ObjectUtils.isEmpty(documentNumber)) {
                //获取文号
                rollback = getDocumentNumberByPublicSecurity(caseDocumentRecord.getDocumentCatalogCode(), caseId, isPublicSecurity, clientOrgCode);
                documentNumber = rollback.getDocumentNumber();
                caseDocumentRecord.setDocumentNumber(documentNumber);
            }
            //设置文号
            jsonObject.put("documentNumber", documentNumber);

            if (PayWayEnum.OFF_SITE.getCode().equals(simpleInfo.getPayWay()) && simpleInfo.getPunishKinds().contains("罚款")
                    && StrUtil.equals(isPublicSecurity, "0")) {
                CasePaymentSlipNumberSaveDto slipNumberSaveDto = new CasePaymentSlipNumberSaveDto();
                slipNumberSaveDto.setCaseId(caseDocumentRecord.getCaseId());
                slipNumberSaveDto.setDocumentCatalogCode(caseDocumentRecord.getDocumentCatalogCode());
                slipNumberSaveDto.setCaseType(CaseTypeEnum.SIMPLE_PROCEDURE.getCode());
                slipNumberSaveDto.setPartyId(caseDocumentRecord.getPartyId());
                // 生成并获取缴费单号
                Result result = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.SAVE_CASE_PAYMENT_MAIN_RECORD, slipNumberSaveDto);
                log.info("生成缴费单结果:{}" + result);
                if (result.getCode() != HttpStatus.HTTP_OK) {
                    throw new BusinessException("生成缴费单失败!" + result.getMessage());
                }
                Map<String, Object> record = JSONObject.parseObject(result.getData().toString(), Map.class);
                String qrUrl = record.get("qrBase64").toString();
                String XZCFJDS_JKDH=record.get("paymentSlipNumber").toString();
                if(!ObjectUtils.isEmpty(qrUrl)){
                    if (!ObjectUtils.isEmpty(qrUrl)) {
                        //SysDepartParam sysDepartParam= sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());
                        jsonObject.put("qrBase64", qrUrl);
                        jsonObject.put("XZCFJDS_JKDH",XZCFJDS_JKDH);
                        /*Map<String,String>  payInfoMap= new HashMap<>(2);
                        payInfoMap.put("XZCFJDS_JKDH", XZCFJDS_JKDH);
                        payInfoMap.put("qrBase64", qrUrl);
                        payInfoMap.put("XZCFJDS_JNFKD",sysDepartParam.getPayBankName());
                        payInfoMap.put("XZCFJDS_SKZH","（户名："+sysDepartParam.getPayBankAccountName()+"，账号："+sysDepartParam.getPayBankAccount()+"）");
                        payInfoList.add(payInfoMap);*/
                        //jsonObject.put("punishKindCheckPayInfo", payInfoList);
                    }
                }

                //base64优化成地址
                //jsonObject.put("qrBase64", record.get("qrUrl"));
            }
        }
        try {
            if (Constant.STRING_KIND_CODE_SDDZQRS.equals(kindCode)) {
                //jsonObject.put("SDDZQRS_QZ", saveDto.getSignFile());
                jsonObject.put("SDDZQRS_QZ", base64Str);
                jsonObject.put("signTime", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
            }
            caseDocumentRecord.setDocumentContent(jsonObject.toJSONString());

            // 重新生成文书
            FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
            if (DocumentKindEnum.DOC_KIND_XCZPJSM.getCode().equals(kindCode) || DocumentKindEnum.DOC_KIND_DK2SJCXGZS.getCode().equals(kindCode)) {
                //现场照片及说明文书设置为标准文书模板
                pdfRequest.setTemplateType(DocumentTemplateKindEnum.STANDARD_TEMPLATE.getCode());
            }
            // 模板类型非空时，赋值
            if (StringUtils.isNotBlank(saveDto.getTemplateType())){
                pdfRequest.setTemplateType(saveDto.getTemplateType());
            }
            HashMap<String, Object> jsonMap = new HashMap<>(64);
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                jsonMap.put(entry.getKey(), entry.getValue());
            }
            pdfRequest.setTemplateCode(templateCode);
            pdfRequest.setParamMap(jsonMap);
            //jsonMap.put("punishKindCheckPayInfo", payInfoList);
            Map<String, String> unSealPdfUrl = appCaseBeforeDocumentRecordService.getConvertedPdfUrl(pdfRequest);

            String unSealPdfUrlStr = unSealPdfUrl.get("fileUrl");
            String pdfSealUrl = unSealPdfUrl.get("fileUrl");
            //判断是否需要签章
            if (YesOrNoEnum.YES.getCode().equals(detailByDocumentCatalogCode.getIsDeptSign())) {
                //CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseDocumentRecord.getCaseId());
                // 签字捺印
                FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
                String entrustClientOrgCode = getEntrustClientOrgCodeIfExists(caseId, caseMainInfo);
                if (StringUtils.isNotEmpty(entrustClientOrgCode)) {
                    SysDepartParam sysDepartParam= sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(entrustClientOrgCode, null);
                    queryDto.setUniscid(sysDepartParam.getUnicode());
                    queryDto.setDeptCode(null);
                } else {
                    SysDepartParam sysDepartParam= sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());
                    queryDto.setUniscid(sysDepartParam.getUnicode());
                    queryDto.setDeptCode(caseMainInfo.getCaseDeptCode());
                }
                queryDto.setFileBase64(unSealPdfUrl.get("fileBase64"));
                pdfSealUrl = appCaseBeforeDocumentRecordService.dealFileSeal(queryDto);
            }

            // 返回
            Map<String, Object> resultMap = new HashMap<>(16);
            resultMap.put("success", "true");
            resultMap.put("pdfSealUrl", pdfSealUrl);
            caseDocumentRecord.setDocumentUrlAfterSign(pdfSealUrl);
            caseDocumentRecord.setDocumentUrlAfterSeal(pdfSealUrl);
            caseDocumentRecord.setDocumentUrlPrint(unSealPdfUrlStr);
            caseDocumentRecord.setSignTime(LocalDateTime.now());
            caseDocumentRecord.setDocumentSignstampedStatus(DocumentStatusEnum.CONFIRM_END.getCode());
            caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecord);

            if (Constant.STRING_KIND_CODE_SDDZQRS.equals(kindCode)) {
                //送达地址确认书确认时更新送达地址确认书表的状态为1
                Example updateExample = new Example(CaseDocumentSendinfoConfirm.class);
                updateExample.createCriteria().andEqualTo("caseId", caseDocumentRecord.getCaseId()).andEqualTo("partyId", caseDocumentRecord.getPartyId());
                CaseDocumentSendinfoConfirm caseDocumentSendinfoConfirm = new CaseDocumentSendinfoConfirm();
                caseDocumentSendinfoConfirm.setStatus(Constant.INTEGER_1);
                caseDocumentSendinfoConfirmMapper.updateByExampleSelective(caseDocumentSendinfoConfirm, updateExample);
            }
            sendAlarm(rollback);
            return resultMap;
        }catch (Exception e){
            // 公安委托执法文号回滚
            publicSecurityRollbackDocumentNumber(rollback);
            if(e instanceof BusinessException){
                throw new BusinessException(e.getMessage());
            }else{
                throw e;
            }
        }
    }

    /**
     * 进行公安委托文号报警判断
     */
    public void sendAlarm(PublicSecurityDocumentNumberRollbackDTO dto) {
        try {
            Boolean rollback = dto.getRollback();
            if (!Objects.isNull(rollback) && rollback) {
                Map<String, String> headers = HeaderUtil.headerInfo();
                String json = JSONObject.toJSONString(dto);
                HttpUtil.createPost(url.concat(PunishMainServicePortUriConstant.PUBLIC_SECURITY_DOCUMENT_NUMBER_ALARM)).addHeaders(headers).body(json).execute().body();
            }
        }catch (Exception e){
            log.error("sendAlarm -> error: {}", e.toString());
        }
    }

    @Override
    public void publicSecurityRollbackDocumentNumber(PublicSecurityDocumentNumberRollbackDTO dto) {
        log.error("publicSecurityRollbackDocumentNumber -> {}", dto);
        Boolean rollback = dto.getRollback();
        if (Boolean.FALSE.equals(rollback)) {
            return;
        }
        // 进行了公安文号委托，后续并发生了报错对公安文号进行回滚
        Map<String, String> headers = HeaderUtil.headerInfo();
        String json = JSONObject.toJSONString(dto);
        String response = HttpUtil.createPost(url.concat(PunishMainServicePortUriConstant.PUBLIC_SECURITY_DOCUMENT_NUMBER_ROLLBACK)).addHeaders(headers).body(json).execute().body();
        Result result = JSON.parseObject(response, Result.class);
        if (ObjectUtils.isEmpty(result) || HttpStatus.HTTP_OK != result.getCode()) {
            log.error("publicSecurityRollbackDocumentNumber -> {}", "文号回滚失败:"+result.getMessage());
        }else {
            log.info("publicSecurityRollbackDocumentNumber -> orgCode:{},documentNumber:{},公安委托文号回滚成功！", dto.getOrgCode(), dto.getDocumentNumber());
        }
    }

    /**
     * 获取文号，公安委托执法获取公安相关的文号
     */
    private PublicSecurityDocumentNumberRollbackDTO getDocumentNumberByPublicSecurity(String documentCatalogCode, String caseId, String isPublicSecurity, String clientOrgCode) {
        PublicSecurityDocumentNumberRollbackDTO rollback = new PublicSecurityDocumentNumberRollbackDTO();
        rollback.setRollback(Boolean.FALSE);
        if (StrUtil.equals(isPublicSecurity, "1") && StrUtil.isNotBlank(clientOrgCode)){
            // 公安委托执法获取对应的文号
            String documentNumber = getPublicSecurityDocumentNumber(clientOrgCode);
            rollback.setDocumentNumber(documentNumber);
            rollback.setOrgCode(clientOrgCode);
            rollback.setRollback(Boolean.TRUE);
            return rollback;
        }
        String commonDocumentNumber = getCommonDocumentNumber(caseId, documentCatalogCode);
        rollback.setDocumentNumber(commonDocumentNumber);
        return rollback;
    }

    private String getEntrustClientOrgCodeIfExists(String caseId, CaseMainInfo caseMainInfo) {
        Example caseReasonMainRecordExample = new Example(CaseReasonMainRecord.class);
        caseReasonMainRecordExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("sxType", "4");
        List<CaseReasonMainRecord> caseReasonMainRecords = caseReasonMainRecordMapper.selectByExample(caseReasonMainRecordExample);
        //当简易程序 && 有委托执法事项时，取委托单位的组织code查询
        if (CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType()) && CollUtil.isNotEmpty(caseReasonMainRecords)) {
            CaseReasonMainRecord caseReasonMainRecord = caseReasonMainRecords.get(Constant.INTEGER_0);
            return caseReasonMainRecord.getClientOrgCode();
        }
        return null;
    }


    /**
     * 描述： 根据caseId查询关联文书列表
     *
     * @return {@link List< CaseDocumentRecord>}
     * @author: zhengqiang
     * @date: 2022/6/21
     * @param: caseId
     **/
    @Override
    public List<CaseDocumentRecordSimpleVo> getDocumentRecordByCaseId(String caseId) {
        List<CaseDocumentRecordSimpleVo> list = new ArrayList<>();
        Example queryExample = new Example(CaseDocumentRecord.class);
        queryExample.createCriteria().andEqualTo("caseId", caseId).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(queryExample);
        caseDocumentRecords.forEach(e -> {
            CaseDocumentRecordSimpleVo vo = new CaseDocumentRecordSimpleVo();
            BeanUtils.copyProperties(e, vo);
            vo.setDocumentId(e.getId());
            list.add(vo);
        });
        return list;
    }

    /**
     * 描述： 生成文书及关联案件
     *
     * @return {@link Map< String, Object>}
     * @author: zhengqiang
     * @date: 2022/6/29
     * @param: saveDto
     **/
    @Override
    public Map<String, Object> saveDocInfoAndRelatedCase(DocSaveAndRelatedCaseDto saveDto) {
        //1.生成文书
        List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos = appCaseBeforeDocumentRecordService.getConfigBusiParamDocumentInfos(saveDto.getDocumentCatalogCode());
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfos.get(0);

        StageDocCommonOperateSaveDto dto = new StageDocCommonOperateSaveDto();
        dto.setCaseId(saveDto.getCaseId());
        dto.setDocumentCatalogCode(saveDto.getDocumentCatalogCode());
        dto.setDataMap(saveDto.getDataMap());
        dto.setPartyId(saveDto.getPartyId());
        if (configBusiParamDocumentInfo.getApplyGroup().contains("ZTC")) {
            dto.setDocumentTemplateType(DocumentTemplateTypeEnum.NARROW_TEMPLATE.getCode());
        }
        Result result = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.SAVE_DOC_INFO, dto);
        log.info("文书生成结果:{}" + result);
        if (result.getCode() != HttpStatus.HTTP_OK) {
            throw new com.icinfo.cloud.provider.common.exception.BusinessException("文书生成失败!" + result.getMessage());
        }
        //stageDocCommonOperateClient.saveDocInfo(dto);

        //2.设置文书关联案件记录
        //查询案件信息
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(saveDto.getCaseId());


        UserDTO userInfo = UserUtil.getUserInfo();
        if (ObjectUtils.isEmpty(userInfo)) {
            throw new com.icinfo.cloud.provider.common.exception.BusinessException("登录失效");
        }
        CaseRelatedDocumentRecord record = new CaseRelatedDocumentRecord();
        record.setCaseId(saveDto.getCaseId());
        record.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
        record.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());
        record.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
        record.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
        record.setCreateUserId(userInfo.getUserId().toString());
        record.setCreateUserName(userInfo.getRealName());

        Example queryExample = new Example(CaseDocumentRecord.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("caseId", saveDto.getCaseId()).andEqualTo("documentCatalogCode", saveDto.getDocumentCatalogCode()).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(caseMainInfo.getCasePartiesReasonType())
                && HandleTypeEnum.MERGE_PUNISH.getCode().equals(caseMainInfo.getHandleType())) {
            if (ObjectUtils.isEmpty(saveDto.getPartyId())) {
                throw new com.icinfo.cloud.provider.common.exception.BusinessException("多当事人合并处罚当事人id不允许为空!");
            }
            criteria.andEqualTo("partyId", saveDto.getPartyId());
        }

        List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(queryExample);
        if (ObjectUtils.isEmpty(caseDocumentRecords)) {
            throw new com.icinfo.cloud.provider.common.exception.BusinessException("文书生成失败!");
        }

        CaseDocumentRecord caseDocumentRecord = caseDocumentRecords.get(0);

        record.setCreateTime(LocalDateTime.now());
        record.setId(BaseUtil.createUid());
        record.setDocumentKindCode(configBusiParamDocumentInfo.getDocumentKindCode());
        record.setDocumentKindName(configBusiParamDocumentInfo.getDocumentKindName());
        record.setDocumentType(configBusiParamDocumentInfo.getDocumentType());
        record.setDocumentId(caseDocumentRecord.getId());
        record.setPartyId(caseDocumentRecord.getPartyId());
        caseRelatedDocumentRecordMapper.insertSelective(record);

        //返回
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("success", "true");
        resultMap.put("docId", caseDocumentRecord.getId());
        resultMap.put("pdfSealUrl", ObjectUtils.isEmpty(caseDocumentRecord.getDocumentUrlAfterSeal()) ? caseDocumentRecord.getDocumentUrl() : caseDocumentRecord.getDocumentUrlAfterSeal());
        resultMap.put("unSealPdfUrl", caseDocumentRecord.getDocumentUrl());
        return resultMap;
    }

    /**
     * 【V1.0.0】描述：根据唯一标识查询文书记录信息
     *
     * @param id 唯一标识
     * @return {@link CaseDocumentRecordVo} 文书记录信息
     * @author xiangyuyu
     * @date 2022-02-25 14:28
     */
    @Override
    public CaseDocumentRecordVo getCaseDocumentRecordInfo(String id) {
        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(caseDocumentRecord)) {
            throw new com.icinfo.cloud.provider.common.exception.BusinessException("未匹配到文书记录");
        }
        CaseDocumentRecordVo vo = new CaseDocumentRecordVo();
        BeanUtils.copyProperties(caseDocumentRecord, vo);
        return vo;
    }

    /**
     * 获取文书记录--通用方法
     *
     * @return {@link CaseDocumentRecord}
     * @author: zhengqiang
     * @date: 2022/5/18
     * @param: caseId
     * @param: documentCatalogCode
     * @param: partyId
     **/
    @Override
    public CaseDocumentRecord getCaseDocumentRecord(String caseId, String documentCatalogCode, String partyId) {
        //查询文书记录数据
        Example example = new Example(CaseDocumentRecord.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        if (!ObjectUtils.isEmpty(partyId)) {
            criteria.andEqualTo("partyId", partyId);
        }
        List<CaseDocumentRecord> caseDocumentRecordList = caseDocumentRecordMapper.selectByExample(example);
        if (caseDocumentRecordList == null || caseDocumentRecordList.size() == 0) {
            return null;
        }
        return caseDocumentRecordList.get(0);
    }
    /**
     * 文书删除
     * @author liyafeng
     * @date 2023/1/12
      * @param caseDocumentRecordDelRequest
     * @return {@link Result< String>}
     */
    @Override
    public Result<String> delCaseDocumentRecordInfo(CaseDocumentRecordDelRequest caseDocumentRecordDelRequest) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String json = JSONObject.toJSONString(caseDocumentRecordDelRequest);
        String response = HttpUtil.createPost(url.concat("punish/ucase/case/main/document/record/delCaseDocumentRecordInfo")).addHeaders(headers).body(json).execute().body();
        Result result = JSON.parseObject(response, Result.class);
        return result;
    }


    /**
     * 获取补正/更正文书的文号
     *
     * @param documentCatalogCode
     * @param caseId              用例id
     * @return {@link String }
     * @author shishengyao
     * @date 2023/02/28
     */
    @Override
    public String getCommonDocumentNumber(String caseId , String documentCatalogCode ){
        Map<String, Object> urlParam = new HashMap<>();
        urlParam.put("caseId", caseId);
        urlParam.put("documentCatalogCode", documentCatalogCode);
        Result result = PunishMainClientUtil.httpGet(PunishMainServicePortUriConstant.GET_DOCUMENT_NUMBER, urlParam);
        if (ObjectUtils.isEmpty(result) || HttpStatus.HTTP_OK != result.getCode() || ObjectUtils.isEmpty(result.getData())) {
            throw new BusinessException("生成文号失败，请联系管理员"+result.getMessage());
        }
        return  result.getData().toString();
    }

    public String getPublicSecurityDocumentNumber(String orgCode){
        Map<String, Object> urlParam = new HashMap<>();
        urlParam.put("orgCode", orgCode);
        Result result = PunishMainClientUtil.httpGet(PunishMainServicePortUriConstant.GET_PUBLIC_SECURITY_DOCUMENT_NUMBER, urlParam);
        if (ObjectUtils.isEmpty(result) || HttpStatus.HTTP_OK != result.getCode() || ObjectUtils.isEmpty(result.getData())) {
            throw new BusinessException("生成文号失败，请联系管理员"+result.getMessage());
        }
        return  result.getData().toString();
    }

    /**
     * 接收 捺印指纹，签字字段保存， 文件重新生成带签字文书
     */
    @Override
    public Map<String, Object> receiveSignFileOfCaseDocChongQing(CaseDocumentRecordSignSaveDto saveDto) {
        // 文书表更新
        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(saveDto.getDocumentId());
        if (caseDocumentRecord == null) {
            throw new BusinessException("文书不存在，请检查");
        }
        String caseId = caseDocumentRecord.getCaseId();
        CaseMainInfo caseMainInfo=caseMainInfoMapper.selectByPrimaryKey(caseId);
        //判断文书目录编码与查询出的文书是否一致
        if (!caseDocumentRecord.getDocumentCatalogCode().equals(saveDto.getDocumentCatalogCode())) {
            throw new BusinessException("入参documentId查询的文书目录编码【" + caseDocumentRecord.getDocumentCatalogCode() + "】与入参documentCatalogCode【" + saveDto.getDocumentCatalogCode() + "】不一致");
        }
        JSONObject jsonObject = JSON.parseObject(caseDocumentRecord.getDocumentContent());
        jsonObject.put("signFingerprintPic", saveDto.getSignFile());
        jsonObject.put("signFingerprintDate", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));

        List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos = appCaseBeforeDocumentRecordService.getConfigBusiParamDocumentInfos(caseDocumentRecord.getDocumentCatalogCode());
        //查询当事人类型
        Example queryExample = new Example(CasePartiesRecord.class);
        queryExample.createCriteria().andEqualTo("caseId", caseDocumentRecord.getCaseId()).andEqualTo("status", "1");
        ;
        List<CasePartiesRecord> casePartiesRecord = casePartiesRecordMapper.selectByExample(queryExample);
        if (ObjectUtils.isEmpty(casePartiesRecord)) {
            throw new BusinessException("未找到当事人信息");
        }
        String partyType = casePartiesRecord.get(0).getPartyType();
        String templateCode = caseDocumentRecord.getDocumentTemplateCode();
        if (ObjectUtils.isEmpty(templateCode)){
            templateCode = appCaseBeforeDocumentRecordService.getTemplateCodeByDocumentCatalogCode(configBusiParamDocumentInfos, partyType,saveDto.getCaseType());
        }
        ConfigBusiParamDocumentInfo detailByDocumentCatalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(caseDocumentRecord.getDocumentCatalogCode());
        String kindCode = detailByDocumentCatalogCode.getDocumentKindCode();
        //简易处罚获取二维码,生成行政行为码
        if (Constant.STRING_KIND_CODE_JYCXCFJDS.equals(kindCode)) {
            //获取文号
            String documentNumber = caseDocumentRecord.getDocumentNumber();
            if (ObjectUtils.isEmpty(documentNumber)) {
                //获取文号
                documentNumber = getCommonDocumentNumber(caseId, caseDocumentRecord.getDocumentCatalogCode());
                caseDocumentRecord.setDocumentNumber(documentNumber);
            }
            //设置文号
            jsonObject.put("documentNumber", documentNumber);

            CaseMainDetailSimpleInfo simpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseId);
            if (PayWayEnum.OFF_SITE.getCode().equals(simpleInfo.getPayWay()) && simpleInfo.getPunishKinds().contains("罚款")) {
                CasePaymentSlipNumberSaveDto slipNumberSaveDto = new CasePaymentSlipNumberSaveDto();
                slipNumberSaveDto.setCaseId(caseDocumentRecord.getCaseId());
                slipNumberSaveDto.setDocumentCatalogCode(caseDocumentRecord.getDocumentCatalogCode());
                slipNumberSaveDto.setCaseType(CaseTypeEnum.SIMPLE_PROCEDURE.getCode());
                slipNumberSaveDto.setPartyId(caseDocumentRecord.getPartyId());
                // 生成并获取缴费单号
                Result result = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.SAVE_CASE_PAYMENT_MAIN_RECORD, slipNumberSaveDto);
                log.info("生成缴费单结果:{}" , result);
                if (result.getCode() != HttpStatus.HTTP_OK) {
                    throw new BusinessException("生成缴费单失败!" + result.getMessage());
                }
                Map<String, Object> record = JSONObject.parseObject(result.getData().toString(), Map.class);
//                String qrUrl = record.get("qrBase64").toString();
                // todo 测试数据
                String qrUrl =  "http://www.baidu.com";
                String XZCFJDS_JKDH=record.get("paymentSlipNumber").toString();
                if(!ObjectUtils.isEmpty(qrUrl)){
                    if (!ObjectUtils.isEmpty(qrUrl)) {
                        jsonObject.put("qrBase64", qrUrl);
                        jsonObject.put("XZCFJDS_JKDH",XZCFJDS_JKDH);
                    }
                }
            }
        }
        if (Constant.STRING_KIND_CODE_SDDZQRS.equals(kindCode)) {
            jsonObject.put("SDDZQRS_QZ", saveDto.getSignFile());
            jsonObject.put("signTime", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
        }
        caseDocumentRecord.setDocumentContent(jsonObject.toJSONString());

        // 重新生成文书
        FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
        if (DocumentKindEnum.DOC_KIND_XCZPJSM.getCode().equals(kindCode) || DocumentKindEnum.DOC_KIND_DK2SJCXGZS.getCode().equals(kindCode)) {
            //现场照片及说明文书设置为标准文书模板
            pdfRequest.setTemplateType(DocumentTemplateKindEnum.STANDARD_TEMPLATE.getCode());
        }
        // 模板类型非空时，赋值
        if (StringUtils.isNotBlank(saveDto.getTemplateType())){
            pdfRequest.setTemplateType(saveDto.getTemplateType());
        }
        HashMap<String, Object> jsonMap = new HashMap<>(64);
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            jsonMap.put(entry.getKey(), entry.getValue());
        }
        pdfRequest.setTemplateCode(templateCode);
        pdfRequest.setParamMap(jsonMap);
        //jsonMap.put("punishKindCheckPayInfo", payInfoList);
        Map<String, String> unSealPdfUrl = appCaseBeforeDocumentRecordService.getConvertedPdfUrl(pdfRequest);

        String unSealPdfUrlStr = unSealPdfUrl.get("fileUrl");
        String pdfSealUrl = unSealPdfUrl.get("fileUrl");
        //判断是否需要签章
        if (YesOrNoEnum.YES.getCode().equals(detailByDocumentCatalogCode.getIsDeptSign())) {
            // todo 签章的文件地址
            pdfSealUrl =appCaseBeforeDocumentRecordService.base64PdfToOssUrl(saveDto.getSignFile());
        }

        // 返回
        Map<String, Object> resultMap = new HashMap<>(16);
        resultMap.put("success", "true");
        resultMap.put("pdfSealUrl", pdfSealUrl);
        caseDocumentRecord.setDocumentUrlAfterSign(pdfSealUrl);
        caseDocumentRecord.setDocumentUrlAfterSeal(pdfSealUrl);
        caseDocumentRecord.setDocumentUrlPrint(unSealPdfUrlStr);
        caseDocumentRecord.setSignTime(LocalDateTime.now());
        caseDocumentRecord.setDocumentSignstampedStatus(DocumentStatusEnum.CONFIRM_END.getCode());
        caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecord);

        if (Constant.STRING_KIND_CODE_SDDZQRS.equals(kindCode)) {
            //送达地址确认书确认时更新送达地址确认书表的状态为1
            Example updateExample = new Example(CaseDocumentSendinfoConfirm.class);
            updateExample.createCriteria().andEqualTo("caseId", caseDocumentRecord.getCaseId()).andEqualTo("partyId", caseDocumentRecord.getPartyId());
            CaseDocumentSendinfoConfirm caseDocumentSendinfoConfirm = new CaseDocumentSendinfoConfirm();
            caseDocumentSendinfoConfirm.setStatus(Constant.INTEGER_1);
            caseDocumentSendinfoConfirmMapper.updateByExampleSelective(caseDocumentSendinfoConfirm, updateExample);
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> receiveSignFileIdOfCaseDocChongQing(SimpleCaseSignFileIdSaveDto saveDto) {
        Map resultMap = new HashMap();
        //简易程序文书种类列表
        List<String> simpleCaseDocs = Arrays.asList(DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode(), DocumentKindEnum.DOC_KIND_XCZPJSM.getCode());

        //查询交易处罚文书列表
        Example queryExample = new Example(CaseDocumentRecord.class);
        queryExample.createCriteria().andEqualTo("caseId", saveDto.getCaseId()).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(queryExample);
        if (ObjectUtils.isEmpty(caseDocumentRecords)) {
            throw new BusinessException("案件id对应文书不存在-caseId:" + saveDto.getCaseId());
        }
        // 获取下载文件的base64
        String base64Data = appCaseBeforeDocumentRecordService.getFileByteByFileId(saveDto.getFileId());
        saveDto.setSignFile(base64Data);
        boolean isSuccess = true;
        List docResultList = new ArrayList();
        for (CaseDocumentRecord e : caseDocumentRecords) {
            Map docResultMap = new HashMap();
            CaseDocumentRecordSignSaveDto dto = new CaseDocumentRecordSignSaveDto();
            dto.setDocumentId(e.getId());
            dto.setSignFile(saveDto.getSignFile());
            dto.setFingerprint(saveDto.getFingerprint());
            dto.setDocumentCatalogCode(e.getDocumentCatalogCode());
            //查询文书种类
            ConfigBusiParamDocumentInfo detailByDocumentCatalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(e.getDocumentCatalogCode());
            String kindCode = detailByDocumentCatalogCode.getDocumentKindCode();
            if (!simpleCaseDocs.contains(kindCode)) {
                continue;
            }
            Map<String, Object> stringObjectMap = receiveSignFileOfCaseDocChongQing(dto);
            if (!"true".equals(stringObjectMap.get("success"))) {
                isSuccess = false;
                break;
            }
            docResultMap.put("documentCatalogCode", e.getDocumentCatalogCode());
            docResultMap.put("pdfSealUrl", stringObjectMap.get("pdfSealUrl"));
            docResultList.add(docResultMap);
        }

        if (!isSuccess) {
            resultMap.put("success", false);
        } else {
            resultMap.put("success", true);
            resultMap.put("docResultList", docResultList);
        }
        return resultMap;
    }

    @Override
    public List<AppAskNoticeDocumentVo> getAppAskNoticeDocumentDetail(AppAskNoticeDto appAskNoticeDto) {
        String caseId = appAskNoticeDto.getCaseId();
        String documentCatalogCode = appAskNoticeDto.getDocumentCatalogCode();
        DocCommonHtmlRequest request = new DocCommonHtmlRequest();
        request.setDocumentCatalogCode(documentCatalogCode);
        CaseReasonMainRecord caseReasonMainRecord = getCaseReasonMainRecord(caseId);
        List<AppAskNoticeDocumentVo> appAskNoticeDocumentVos = new ArrayList();
        // 查询案件id对应的抽样取证通知书
        AppAskNoticeDocumentVo appAskNoticeDocumentByCaseIdVo = new AppAskNoticeDocumentVo();
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = getConfigBusiParamDocumentInfo(documentCatalogCode);
        if (configBusiParamDocumentInfo!=null) {
            String relationDocumentCatalogCode = configBusiParamDocumentInfo.getRelationDocumentCatalogCode();
            if (StringUtils.isNotBlank(relationDocumentCatalogCode)) {
                ConfigBusiParamDocumentInfo configBusiParamDocumentInfo2 = getConfigBusiParamDocumentInfo(relationDocumentCatalogCode);
                if (configBusiParamDocumentInfo2!=null) {
                    appAskNoticeDocumentByCaseIdVo.setDocumentName(configBusiParamDocumentInfo2.getDocumentCatalogName());
                    if (StringUtils.isNotBlank(caseId)) {
                        CaseDocumentRecord caseDocumentRecord = getCaseDocumentRecord(caseId, relationDocumentCatalogCode);
                        if (caseDocumentRecord!=null) {
                            appAskNoticeDocumentByCaseIdVo.setDocumentNumber(caseDocumentRecord.getDocumentNumber());
                            if (!caseDocumentRecord.getDocumentContent().isEmpty()) {
                                // 取出documentContent中的goodsList
                                JSONObject jsonObject = JSONObject.parseObject(caseDocumentRecord.getDocumentContent());
                                Object goodsList = jsonObject.get("goodsList");
                                if (Objects.nonNull(goodsList)) {
                                    appAskNoticeDocumentByCaseIdVo.setGoodsList(JSONArray.parseArray(goodsList.toString(),AppDocumentRelatedGoods.class));
                                }
                                if (caseReasonMainRecord!=null) {
                                    appAskNoticeDocumentByCaseIdVo.setIllegalBasis(caseReasonMainRecord.getIllegalBasis());
                                    appAskNoticeDocumentByCaseIdVo.setFlag(Constant.STRING_1);
                                    appAskNoticeDocumentByCaseIdVo.setCaseId(caseReasonMainRecord.getCaseId());
                                    appAskNoticeDocumentByCaseIdVo.setDocumentCatalogCode(documentCatalogCode);
                                    appAskNoticeDocumentVos.add(appAskNoticeDocumentByCaseIdVo);
                                }
                            }
                        }
                    }
                }
            }
        }
        // 查询直通车的文书
        List<AppRelationDocumentListVo> relationDocumentListByCatalogCode = appCaseBeforeDocumentRecordServiceImpl.getRelationDocumentListByCatalogCode(request);
        if (!ObjectUtils.isEmpty(relationDocumentListByCatalogCode)) {
            for (AppRelationDocumentListVo appRelationDocumentListVo : relationDocumentListByCatalogCode) {
                AppAskNoticeDocumentVo appAskNoticeDocumentVo = new AppAskNoticeDocumentVo();
                String ztcDocumentId = appRelationDocumentListVo.getDocumentId();
                Example example = new Example(AppDocumentRelatedGoods.class);
                example.createCriteria().andEqualTo("documentId", ztcDocumentId);
                List<AppDocumentRelatedGoods> goodsList = appDocumentRelatedGoodsMapper.selectByExample(example);
                if (!goodsList.isEmpty()) {
                    appRelationDocumentListVo.setGoodsList(goodsList);
                }
                BeanUtils.copyProperties(appRelationDocumentListVo, appAskNoticeDocumentVo);
                if (caseReasonMainRecord!=null) {
                    appAskNoticeDocumentVo.setIllegalBasis(caseReasonMainRecord.getIllegalBasis());
                }
                appAskNoticeDocumentVo.setFlag(Constant.STRING_0);
                appAskNoticeDocumentVo.setCaseId(caseReasonMainRecord.getCaseId());
                appAskNoticeDocumentVo.setDocumentCatalogCode(documentCatalogCode);
                appAskNoticeDocumentVos.add(appAskNoticeDocumentVo);
            }
        }
        return appAskNoticeDocumentVos;
    }

    public ConfigBusiParamDocumentInfo getConfigBusiParamDocumentInfo(String documentCatalogCode) {
        Example configBusiParamDocumentInfoExample = new Example(ConfigBusiParamDocumentInfo.class);
        configBusiParamDocumentInfoExample.createCriteria().andEqualTo("documentCatalogCode", documentCatalogCode);
        List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos = configBusiParamDocumentInfoMapper.selectByExample(configBusiParamDocumentInfoExample);
        if (!configBusiParamDocumentInfos.isEmpty()) {
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfos.get(Constant.INTEGER_0);
            return configBusiParamDocumentInfo;
        }
        return null;
    }

    public CaseDocumentRecord getCaseDocumentRecord(String caseId, String documentCatalogCode) {
        Example example = new Example(CaseDocumentRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("documentRecordStatus", '1').andEqualTo("documentSignstampedStatus","SIGN_1");
        List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(caseDocumentRecords)) {
            CaseDocumentRecord caseDocumentRecord = caseDocumentRecords.get(Constant.INTEGER_0);
            return caseDocumentRecord;
        }
        return null;
    }

    public CaseReasonMainRecord getCaseReasonMainRecord(String caseId) {
        Example example = new Example(CaseReasonMainRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId);
        List<CaseReasonMainRecord> caseReasonMainRecords = caseReasonMainRecordMapper.selectByExample(example);
        if (!caseReasonMainRecords.isEmpty()) {
            CaseReasonMainRecord caseReasonMainRecord = caseReasonMainRecords.get(Constant.INTEGER_0);
            return caseReasonMainRecord;
        }
        return null;
    }
}
